# core/file_operations.py - 文件操作
import json
from pathlib import Path
from typing import Dict, Any

class FileOperations:
    """文件操作类 - 负责文件相关的操作"""
    
    def __init__(self, config):
        self.config = config
    
    def load_local_index(self) -> Dict[str, Any]:
        """加载本地文件索引"""
        index_file = self.config.cache_dir / "files.json"
        if index_file.exists():
            try:
                with open(index_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except Exception:
                return {"files": []}
        else:
            return {"files": []}
    
    def save_local_index(self, files_index: Dict[str, Any]):
        """保存文件索引到本地缓存"""
        index_file = self.config.cache_dir / "files.json"
        with open(index_file, 'w', encoding='utf-8') as f:
            json.dump(files_index, f, ensure_ascii=False, indent=2)
    
    def download_remote_index(self, cloud_sync, remote_path: str) -> bool:
        """下载远程文件索引"""
        local_index_path = self.config.cache_dir / "remote_files.json"
        success = cloud_sync.download_file(remote_path, str(local_index_path))
        
        if success and local_index_path.exists():
            with open(local_index_path, 'r', encoding='utf-8') as f:
                remote_index = json.load(f)
            
            # 保存到本地索引
            with open(self.config.cache_dir / "files.json", 'w', encoding='utf-8') as f:
                json.dump(remote_index, f, ensure_ascii=False, indent=2)
            
            # 清理临时文件
            local_index_path.unlink(missing_ok=True)
            return True
        return False
    
    def upload_files_index(self, cloud_sync, files_index: Dict[str, Any], remote_path: str) -> bool:
        """上传文件索引到WebDAV"""
        # 保存到临时文件
        temp_index = self.config.cache_dir / "temp_files.json"
        try:
            with open(temp_index, 'w', encoding='utf-8') as f:
                json.dump(files_index, f, ensure_ascii=False, indent=2)
            
            # 上传到WebDAV
            success = cloud_sync.upload_file(str(temp_index), remote_path)
            return success
            
        except Exception as e:
            print(f"上传文件索引异常: {str(e)}")
            return False
        finally:
            # 清理临时文件
            if temp_index.exists():
                temp_index.unlink()
    
    def upload_file_content(self, cloud_sync, content: str, remote_path: str) -> bool:
        """上传文件内容到WebDAV"""
        # 保存到临时文件
        temp_file = self.config.cache_dir / "temp_upload.txt"
        try:
            with open(temp_file, 'w', encoding='utf-8') as f:
                f.write(content)
            
            # 上传到WebDAV
            success = cloud_sync.upload_file(str(temp_file), remote_path)
            return success
            
        except Exception as e:
            print(f"上传文件异常: {str(e)}")
            return False
        finally:
            # 清理临时文件
            if temp_file.exists():
                temp_file.unlink()